package ar.edu.unq.tpi.uis.tepe3.wicket.pages;

import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;

import ar.edu.unq.tpi.uis.tepe3.dominio.Group;
import ar.edu.unq.tpi.uis.tepe3.dominio.exception.GrantableModelValidationException;
import ar.edu.unq.tpi.uis.tepe3.wicket.AbstractFormPage;
import ar.edu.unq.tpi.uis.tepe3.wicket.WicketApplication;

public class GroupFormPage extends AbstractFormPage{

	public GroupFormPage() {
		super("Crear nuevo grupo");
		
		Group aGroup = new Group("");
		this.setModel(new CompoundPropertyModel(aGroup));
		initializeForm(GroupListPage.class);
	}

	public GroupFormPage(IModel model) {
		super("Modificar Grupo", model);
		this.isNew = false;
		initializeForm(GroupListPage.class);
	}

	
	protected void addFields() {
		aForm.add(new FeedbackPanel("feedback"));
		aForm.add(new TextField("id").setRequired(true));
	}
	
	@Override
	protected void saveAction() {
		Group aGroup = (Group) getModelObject();
		try {
			aGroup.validate();
			// TODO: Sacar responsabilidad,solo guardar no debe saber si es nuevo o no.
			if(this.isNew){
				((WicketApplication) this.getApplication()).getModel().addGroup(aGroup);
			}
			((WicketApplication) this.getApplication()).save();
			saveSucceed();
		} catch (Exception e) {
			// FIXME: Esto es por que estoy trabajando en memoria y no realmente con db4o
			((WicketApplication) this.getApplication()).getModel().removeGroup(aGroup);
			warn(e.getMessage());
		}
		
	}

}
